/*
 * @Author: your name
 * @Date: 2021-06-16 17:00:31
 * @LastEditTime: 2024-08-14
 * @LastEditors: Tommy Chen
 * @Description: 用户信息缓存
 * @FilePath: /macc.admin.vue/src/projectCommon/store/modules/user/index.js
 */
import { maccApi, requestHttp, requestSystemConf } from '@utils/index';
import { i18nRender } from '@/locales';
const state = {
  access_token: sessionStorage.getItem('access_token') || null,
  hasLogin: false,
  userType: 'ROOT',
  project: 0,
  warnCount: 0,
  recommendUpgradDevice: 0,
  userInfo: null,
  tenantId: self != top ? top?.base?.css2 && parseInt(top?.base?.css2) : null, //默认取副页面中css2存储的当前租户
  tenantInfo: {},
  isShareMode: false, // 是否用户切换到了分享（托管）模式
  rootTenantId: null, //根租户的tenantId
  sysConf: null,
  lastRequestFailObj: {}, // tommy 24.3.25 防止重复请求
};

const mutations = {
  SET_LAST_REQUEST_FAIL(state, payload) {
    state.lastRequestFailObj = payload;
  },
  SET_TOKEN(state, payload) {
    state.access_token = payload;
    sessionStorage.setItem('access_token', payload);
  },
  SET_PROJECT(state, payload) {
    state.project = payload;
  },
  SET_LOGIN(state, payload) {
    state.hasLogin = payload;
    sessionStorage.setItem('hasLogin', payload);
  },

  SET_CURRENT_TENANTID(state, payload) {
    state.tenantId = payload;
  },

  CLEAR_TOKEN() {
    // state.access_token = null;
    state.hasLogin = false;
    //直接clear会导致所有得sessionStorage被清除，造成父框架得数据丢失
    //sessionStorage.clear();
    sessionStorage.removeItem('hasLogin');
    sessionStorage.removeItem('userType');
  },
  TOP_LOGINOUT() {
    //判断是否主框架
    if (window.top != window) {
      //主框架登出操作
      window.top.location = window.top.base.cxt + '/login/exit';
    }
  },
  SET_USERTYPE(state, payload) {
    state.userType = payload;
    sessionStorage.setItem('userType', payload);
  },
  SET_WARNCOUNT(state, payload) {
    state.warnCount = payload;
  },
  SET_RECOMMENDDEVICECOUNT(state, payload) {
    state.recommendUpgradDevice = payload;
  },
  SET_USER_INFO(state, payload) {
    state.userInfo = payload;
  },
  SET_CURRENT_IS_SHARE_MODE(state, payload) {
    state.isShareMode = payload;
    sessionStorage.setItem('isShareMode', payload);
  },
  SET_ROOT_TENSNT(state, payload) {
    state.rootTenantId = payload;
  },
  SET_SYSTEM_CONF(state, payload) {
    state.sysConf = payload;
  },
  SET_TENANT_INFO(state, payload) {
    state.tenantInfo = payload;
  },
};

const actions = {
  //获取用户登录信息
  getUserInfo({ commit, dispatch, rootState }) {
    const self = this;
    return new Promise((resolve, reject) => {
      var data = {
        api: maccApi.ACCOUNT_INFO,
        method: 'GET',
      };
      requestHttp(data)
        .then((res) => {
          if (res && res.code == 0) {
            if (res.tenantRole === 'VOUCHER' && res.theme !== 'RUIYI') {
              dispatch('switchRuiyiTheme');
            }

            commit('SET_LOGIN', true);
            commit('SET_USERTYPE', res.userType);
            commit('SET_USER_INFO', res);

            const languageObjMap = {
              cn: 'zh',
            };
            let language = '';
            if (res.language) {
              language = languageObjMap[res.language] || res.language;
              // 目前海外云端的只有en和zh，就是中英文的环境，有的时候有些用户app上选择的是小语种环境，导致接口返的是小语种变量，但是云端这边只支持中英文，要把小语种变量转成中英文变量跳转
              // if (process.env.VUE_APP_MACC_ENV == 'INTL') {
              //   language = language == 'zh' ? 'zh' : 'en';
              // }
            } else {
              language = process.env.VUE_APP_MACC_DEFAULT_LANGUAGE;
            }
            dispatch('I18n/setLang', language, { root: true });
            resolve();
          } else {
            reject({
              msg: res?.msg || i18nRender('gatewayVlanConf.getUserMsgFail'),
            });
          }
        })
        .catch((error) => {
          reject({
            msg:
              i18nRender('gatewayVlanConf.getUserMsgFail') +
              `:${JSON.stringify(error)}`,
          });
        });
    });
  },

  async switchRuiyiTheme({ commit, dispatch, rootState }) {
    const { origin } = window.location;
    if (process.env.VUE_APP_MACC_ENV === 'INTL') {
      var data = {
        api: maccApi.GET_USER_THEME,
        method: 'PUT',
        params: {
          theme: 'RUIYI',
        },
      };
      let res = await requestHttp(data);

      if (res && res.code == 0) {
        window.top.location = `${origin}/admin3/`;
      } else {
        this.$message.error(res.msg);
      }
    }
  },

  getTenantInfo({ commit }) {
    return new Promise((resolve, reject) => {
      var data = {
        api: maccApi.GET_USER_LOGO_API,
        method: 'GET',
      };
      requestHttp(data)
        .then((res) => {
          if (res && res.code == 0) {
            const tenantInfo = { ...res };
            delete tenantInfo.code;
            delete tenantInfo.msg;
            commit('SET_TENANT_INFO', tenantInfo);
            const { tenantId } = tenantInfo;
            if (tenantId) {
              commit('SET_CURRENT_TENANTID', tenantId);
            }
            resolve();
          } else {
            reject({
              msg: res?.msg || i18nRender('gatewayVlanConf.getUserMsgFail2'),
            });
          }
        })
        .catch((error) => {
          reject({
            msg:
              i18nRender('gatewayVlanConf.getUserMsgFail2') +
              `:${JSON.stringify(error)}`,
          });
        });
    });
  },
  //用户告警统计
  getWarnCount({ commit }) {
    return new Promise((resolve, reject) => {
      var data = {
        api: maccApi.WARN_COUNT_GET_API,
        method: 'GET',
      };
      requestHttp(data)
        .then((res) => {
          if (res && res.code == 0) {
            commit('SET_WARNCOUNT', res.data);
            resolve();
          } else {
            reject(res);
          }
        })
        .catch((error) => {
          reject(error);
        });
    });
  },
  //推荐升级数量统计
  getRecommendUpgradDevice({ commit }) {
    return new Promise((resolve, reject) => {
      var data = {
        api: maccApi.INDEX_DEVICE_RECOMMENDDEVICECOUNT_GET_API,
        method: 'GET',
      };
      requestHttp(data)
        .then((res) => {
          if (res && res.code == 0) {
            commit('SET_RECOMMENDDEVICECOUNT', res.deviceTotalNum);
            resolve();
          } else {
            reject(res);
          }
        })
        .catch((error) => {
          reject(error);
        });
    });
  },
  setProject({ commit }, status) {
    commit('SET_PROJECT', status);
  },
  //获取系统配置
  getSysConf({ commit }) {
    return new Promise((resolve, reject) => {
      requestSystemConf()
        .then((res) => {
          if (res && res.code == 0) {
            commit('SET_SYSTEM_CONF', res.data);
            resolve();
          } else {
            reject({
              msg: res.msg || i18nRender('gatewayVlanConf.getSystemConfFail'),
            });
          }
        })
        .catch((error) => {
          reject({
            msg: i18nRender('gatewayVlanConf.getSystemConfFail'),
          });
        });
    });
  },

  // userLogin({ commit }, userInfo) {
  //   const appid = process.env.VUE_APP_MACC_APPID;
  //   const secret = process.env.VUE_APP_MACC_SECRET;
  //   return new Promise((resolve, reject) => {
  //     var data = {
  //       api: `service/api/login?appid=${appid}&secret=${secret}&account=${userInfo.account}&password=${userInfo.password}`,
  //       method: 'GET',
  //     };
  //     requestHttp(data)
  //       .then((res) => {
  //         if (res && res.code == 0) {
  //           commit('SET_TOKEN', res.access_token);
  //           commit('SET_LOGIN', true);
  //           resolve();
  //         } else {
  //           reject(res);
  //         }
  //       })
  //       .catch((error) => {
  //         reject(error);
  //       });
  //   });
  // },
};

const getters = {};

export default {
  namespaced: true, //开启命名空间，更好的区分使用stage,防止不同stage模块中的方法重名
  state,
  getters,
  mutations,
  actions,
};
